package com.dxtan90.strategy.impl;

import com.dxtan90.strategy.BaseStrategy;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author shijunhao
 * @since 2024/4/16 14:03
 */
public class Scccts extends BaseStrategy {

    @Override
    public String getSourceUrl() {
        return "https://www.scccts.com";
    }

    @Override
    public String getCategoryName() {
        return "scccts";
    }


    @Override
    public String parseTitle(Document document) {
        return Optional.ofNullable(document.getElementById("info"))
                .map(elements -> elements.child(0))
                .map(Element::text)
                .orElse("noneTitle_" + System.currentTimeMillis());
    }

    @Override
    public List<String> parseCategory(Document document) {
        List<String> category = new ArrayList<>();
        Elements dl = Optional.ofNullable(document.getElementById("list"))
                .map(element -> element.child(0).children())
                .orElse(new Elements());
        int dtCount = 0;
        for (Element dd : dl) {
            if ("dt".equals(dd.tagName())) {
                dtCount++;
            }
            if (dtCount > 1 && "dd".equals(dd.tagName())) {
                Optional.of(dd.child(0)).ifPresent(a -> {
                    String href = a.attr("href");
                    category.add(href);
                });
            }
        }
        return category;
    }

    @Override
    public List<String> parseContent(Document document) throws IOException {
        List<String> sectionList = new ArrayList<>();
        String text = Optional.ofNullable(document.getElementById("content"))
                .map(Element::html)
                .orElse("");
        String[] split = text.split("<br>");
        for (String s : split) {
            if (!StringUtils.isBlank(s)) {
                Document lineDoc = Jsoup.parse(s);
                if (lineDoc.getElementsByTag("p").size() > 0) {
                    continue;
                }
                String newText = lineDoc.text();
                sectionList.add(newText);
            }
        }
        return sectionList;
    }

}